package com.exercise.widgets.recyclerview.selection

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.PopupMenu.OnMenuItemClickListener
import androidx.recyclerview.selection.SelectionPredicates
import androidx.recyclerview.selection.SelectionTracker
import androidx.recyclerview.selection.StorageStrategy
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView.VERTICAL
import com.exercise.struct.base.BaseActivity
import com.exercise.widgets.R
import com.exercise.widgets.databinding.ActivitySelectionListBinding
import com.exercise.widgets.recyclerview.selection.adapter.ContactAdapter
import com.exercise.widgets.recyclerview.selection.entity.Contact
import com.exercise.widgets.recyclerview.selection.selector.ContactItemDetailLookup
import com.exercise.widgets.recyclerview.selection.selector.ContactKeyProvider
import com.exercise.widgets.recyclerview.selection.viewmodel.SelectionListViewModel

class SelectionListActivity : BaseActivity<SelectionListViewModel, ActivitySelectionListBinding>() {
    override val bindingInflater: (LayoutInflater) -> ActivitySelectionListBinding
        get() = ActivitySelectionListBinding::inflate
    override val modelClass: Class<SelectionListViewModel>
        get() = SelectionListViewModel::class.java

    private val mAdapter by lazy {
        ContactAdapter(onClickEdit = { view, position ->
            PopupMenu(this, view).apply {
                setOnMenuItemClickListener(OnMenuItemClick(
                    onClickDelete = {
                        Toast.makeText(
                            this@SelectionListActivity,
                            "Delete: $position",
                            Toast.LENGTH_SHORT
                        ).show()
                    },
                    onClickFavorite = {
                        Toast.makeText(
                            this@SelectionListActivity,
                            "Favorite: $position",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                ))
                inflate(R.menu.menu_pop_menu)
            }.also {
                it.show()
            }
        })
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_pop_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.apple, R.id.pear, R.id.banana -> {
                item.isChecked = !item.isChecked
                true
            }
            else   ->{
                super.onOptionsItemSelected(item)
            }
        }
    }

    private class OnMenuItemClick(
        private val onClickDelete: () -> Unit,
        private val onClickFavorite: () -> Unit
    ) : OnMenuItemClickListener {
        override fun onMenuItemClick(item: MenuItem?): Boolean {
            return when (item?.itemId) {
                R.id.action_delete -> {
                    onClickDelete()
                    true
                }

                R.id.action_favorite -> {
                    onClickFavorite()
                    true
                }


                else -> false
            }
        }

    }

//    override fun onOptionsItemSelected(item: MenuItem): Boolean {
//        return when (item.itemId) {
//            R.id.apple,R.id.pear,R.id.banana -> {
//                item.isChecked = !item.isChecked
//                true
//            }
//            else -> super.onOptionsItemSelected(item)
//        }
//    }


    override fun initView() {
        initPageView()
        initObserver()
    }

    override fun initData() {
        mViewModel.loadData()
    }

    private fun initPageView() {
        binding.recyclerView.run {
            adapter = mAdapter
            addItemDecoration(DividerItemDecoration(context, VERTICAL))
        }
        mAdapter.tracker = SelectionTracker.Builder(
            "selection-1",
            binding.recyclerView,
            ContactKeyProvider(mAdapter),
            ContactItemDetailLookup(binding.recyclerView),
            StorageStrategy.createParcelableStorage(Contact::class.java)
        )
            .withSelectionPredicate(SelectionPredicates.createSelectSingleAnything())
            .build().apply {
                addObserver(object : SelectionTracker.SelectionObserver<Contact>() {
                    override fun onSelectionChanged() {
                        super.onSelectionChanged()
                        mAdapter.tracker?.selection?.forEach {
                            Log.d("SelectionListActivity", "onSelectionChanged: $it")
                        }
                    }
                })
            }
    }

    private fun initObserver() {
        mViewModel.contacts.observe(this) { contacts ->
            mAdapter.setList(contacts)
        }
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        mAdapter.tracker?.onRestoreInstanceState(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mAdapter.tracker?.onSaveInstanceState(outState)
    }

    companion object {
        fun start(context: Context) {
            Intent(context, SelectionListActivity::class.java)
                .also {
                    context.startActivity(it)
                }
        }
    }

}